//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client;

import tv.dyndns.kishibe.client.game.SceneGame;
import tv.dyndns.kishibe.client.packet.PacketMatchingPlayer;
import tv.dyndns.kishibe.client.packet.PacketProblemData;
import tv.dyndns.kishibe.client.util.SerialTimer;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class SceneReadyForGame implements SceneBase {
	private final PanelReadyForGame panel = new PanelReadyForGame();
	private PacketProblemData[] problemData;
	private PacketMatchingPlayer[] players;
	private final Timer timerWaitForGame = new SerialTimer() {
		public void run() {
			waitForGame();
		}
	};
	private final Timer timerRecieveDatas = new SerialTimer() {
		public void run() {
			recieveProblemData();
			recievePlayerData();
		}
	};
	private final boolean addPenalty;

	public SceneReadyForGame(boolean addPenalty) {
		this.addPenalty = addPenalty;
		Controller.getInstance().setGamePanel(panel);

		SoundPlayer.getInstance().play(Constant.SOUND_URL_READY_FOR_GAME);
	}

	private void waitForGame() {
		final int sessionId = SharedData.getInstance().getSessionId();
		Service.Util.getInstance().waitForGame(sessionId, callbackWaitForGame);
	}

	private final AsyncCallback<Integer> callbackWaitForGame = new AsyncCallback<Integer>() {
		public void onSuccess(Integer result) {
			if (panel == null) {
				return;
			}
			panel.setRestSecond(result);

			if (result <= 0) {
				if (problemData == null) {
					Controller.getInstance().showErrorMessage("問題の取得に失敗しました\nF5を押してリロードしてください");
					return;
				}

				Controller.getInstance().setScene(new SceneGame(problemData, players, addPenalty));
				problemData = null;
				timerWaitForGame.cancel();

				return;
			}
		}

		public void onFailure(Throwable caught) {
			Controller.getInstance().showErrorMessage("SceneReadyForGame.waitForGame() - 待機状態の取得に失敗しました。");
		}
	};

	private void recieveProblemData() {
		// 問題取得
		final int sessionId = SharedData.getInstance().getSessionId();
		Service.Util.getInstance().getProblemData(sessionId, callbackRecieveProblemData);
	}

	private final Timer timerRecieveProblemData = new SerialTimer() {
		public void run() {
			recieveProblemData();
		}
	};

	private final AsyncCallback<PacketProblemData[]> callbackRecieveProblemData = new AsyncCallback<PacketProblemData[]>() {
		public void onSuccess(PacketProblemData[] result) {
			if (result == null) {
				timerRecieveProblemData.schedule(Constant.RETRY_DELAY);
				Controller.getInstance().showErrorMessage("SceneReadyForGame.callbackRecieveProblemData - 無効な問題情報が返されました。パケットを再送します。");
				return;
			}

			problemData = result;
		}

		public void onFailure(Throwable caught) {
			timerRecieveProblemData.schedule(Constant.RETRY_DELAY);
			Controller.getInstance().showErrorMessage("SceneReadyForGame.callbackRecieveProblemData - 問題の取得に失敗しました。パケットを再送します。");
		}
	};

	private void recievePlayerData() {
		// プレイヤー取得
		final int sessionId = SharedData.getInstance().getSessionId();
		Service.Util.getInstance().getMachingPlayer(sessionId, callbackRecievePlayerData);
	}

	private final Timer timerRecievePlayerData = new SerialTimer() {
		public void run() {
			recievePlayerData();
		}
	};

	private final AsyncCallback<PacketMatchingPlayer[]> callbackRecievePlayerData = new AsyncCallback<PacketMatchingPlayer[]>() {
		public void onSuccess(PacketMatchingPlayer[] result) {
			if (result == null) {
				timerRecievePlayerData.schedule(Constant.RETRY_DELAY);
				Controller.getInstance().showErrorMessage("SceneReadyForGame.callbackRecievePlayerData - 無効なプレイヤーリストが返されました。パケットを再送します。");
				return;
			}

			players = result;
			panel.setPlayerList(players);
		}

		public void onFailure(Throwable caught) {
			timerRecievePlayerData.schedule(Constant.RETRY_DELAY);
			Controller.getInstance().showErrorMessage("SceneReadyForGame.callbackRecievePlayerData - プレイヤーリストの取得に失敗しました。パケットを再送します。");
		}
	};

	public void onLoad() {
		timerRecieveDatas.schedule(2000);
		timerWaitForGame.scheduleRepeating(1000);
	}

	public void onUnload() {
		timerRecieveDatas.cancel();
		timerWaitForGame.cancel();
		timerRecievePlayerData.cancel();
		timerRecieveProblemData.cancel();
	}
}
